package com.example.a2209_mianshi

import android.content.Context
import android.os.SystemClock
import android.util.TypedValue
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.a2209_mianshi.app.App
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import me.jessyan.autosize.utils.AutoSizeUtils

/**
 * @author jihaosen
 * @description 封装所有扩展函数
 * @date 2025/5/12
 */
fun <T> Flow<T>.observeWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    minState:Lifecycle.State = Lifecycle.State.RESUMED,
    action:suspend (T) ->Unit
):Job = lifecycleOwner.lifecycleScope.launch {
    lifecycleOwner.repeatOnLifecycle(minState){
        collectLatest {
            action.invoke(it)
        }
    }
}
//获取属性值
fun getAttrValue(context: Context, attrId: Int): Int {
    val typedValue = TypedValue()
    context.theme.resolveAttribute(attrId, typedValue, true)
    return typedValue.resourceId
}
val appContext: Context
    get() = App.getAppContext()
val Int.dp: Int
    get() = AutoSizeUtils.dp2px(appContext, this.toFloat())
val Float.dp: Float
    get() = AutoSizeUtils.dp2px(appContext, this).toFloat()
//按键消抖
fun View.clickFlow() = callbackFlow {
    setOnClickListener {
        trySend(Unit).onFailure { e -> e?.printStackTrace() }
    }
    awaitClose { setOnClickListener(null) }
}
fun <T> Flow<T>.throttleFirst(thresholdMillis: Long) = flow {
    var lastTime = 0L
    collect { upstream ->
        val currentTime = SystemClock.elapsedRealtime()
        if (currentTime - lastTime >= thresholdMillis) {
            lastTime = currentTime
            emit(upstream)
        }
    }
}